I've been trying to rewrite the _.defaults method from underscore.js and I keep getting this error:
should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }
Here's the missing conditions:
-should copy source properties to undefined properties in the destination object and should return the destination object
and my code:
_.defaults = function (destination, source) {
Object.keys(destination).forEach(key => {
if (destination[key] === undefined || destination[key] === null) {
destination[key] = source[key];
}
})
return destination;
};
The idea in _.defaults is that keys from the source object might be missing entirely in the destination object. So you need to iterate the keys of the source object instead of those of the destination object:
_.defaults = function (destination, source) {
Object.keys(source).forEach(key => {
if (destination[key] === undefined || destination[key] === null) {
destination[key] = source[key];
}
})
return destination;
};
Side note: you can write x == null instead of x === null || x === undefined. Saves some precious keystrokes.
_.defaults = function (destination, source) {
Object.keys(source).forEach(key => {
if (destination[key] == null) {
destination[key] = source[key];
}
})
return destination;
};